<script setup lang="ts">
// import AppMemberNotificationsMessage from './AppMemberNotificationsMessage.vue'
import { storeToRefs } from 'pinia';
import { useForm } from 'vee-validate';
import * as yup from 'yup';
import type { EnumCurrencyKey, VirtualCoin, availableCurrency } from '~/apis/types';
import type { CurrencyCode } from '~/composables/useCurrencyData';
import { Form } from 'vee-validate';

interface ICurrencyOption extends availableCurrency {
  label: EnumCurrencyKey
  value: CurrencyCode
}
interface IVirAddressOption extends VirtualCoin {
  label: string
  value: string
  disabled: boolean
}
interface IVirCardOption extends VirtualCoin {
  label: string
  value: string
  disabled: boolean
}
interface Props {
  initVirCurrency: availableCurrency
  initVirCurrencyList: ICurrencyOption[]
}
defineOptions({
  name: 'AppWalletWithDrawVirV3',
})
enum SheetType {
  CURRENCY = 1,
  CHAIN
}
const props = defineProps<Props>()
const router = useRouter()
const { t } = useI18n()
// const customRouter = useCustomRouter()
const appStore = useAppStore()
const withdrawFormRef = ref()
const { balanceData, isCompleteKYC, isLogin } = storeToRefs(appStore)
const { isKYCVerifyOpen } = storeToRefs(useBrandStore())
const { bool: isDataLoading } = useBoolean(false)
const { bool: showMaxAmount, setBool: setMaxAmount } = useBoolean(false)
// const { openDeleteConfirm } = useDeleteConfirmDialog()
// const { openPromptDialog } = useDialogPrompt()
// const { openNotify } = useNotify()
const { getVirtualCurrencyContractType } = useCurrencyData()
const { brandAmount } = storeToRefs(useBrandStore())
/** 最大提款额 */
const {
  data: withdrawBalance,
  runAsync: runWithdrawBalance,
} = useRequest(ApiFinanceWithdrawBalance)
/** KYC弹窗 */
// const { openKYCDialog } = useDialogKYCVerify()

const activeVirCurrency = ref(props.initVirCurrency)
const virSearchValue = ref('')
const virCurrencyList = ref(props.initVirCurrencyList)
const currentNetwork = ref(initNetwork())
const amountRef = ref()
const memoRef = ref()
const selectedAmount = ref()
const sheetType = ref(SheetType.CURRENCY)
const showSheet = ref(false)
const showAddressSheet = ref(false)
const addressSelectRef = ref()
const { width } = useElementSize(addressSelectRef)
const maxAmount = computed(() =>
  application.formatNumDecimal(withdrawBalance.value?.withdraw_balance ?? 0, currencyConfig[activeVirCurrency.value.currency_name].decimal),
)
const minWithdraw = computed(() => Number(brandAmount.value ? brandAmount.value[`c${activeVirCurrency.value.currency_id}`].w ?? 0 : 0))
/** 当前是XRP */
const isXRP = computed(() => activeVirCurrency.value.currency_name === 'XRP')
/** 当前是EOS */
const isEOS = computed(() => activeVirCurrency.value.currency_name === 'EOS')

const schema = computed(() => yup.object().shape({
  address: yup.string().required(t('withdraw_address')),
  password: yup.string().required(t('money_password_placeholder')),
  memo: yup.string(),
  amount: yup.number()
    .required(t('recharge_amount_placeholder'))
    .min(minWithdraw.value, t('min_amount', {amount: minWithdraw.value}))
    .max(Number(withdrawBalance.value?.withdraw_balance), t('max_amount', {amount: withdrawBalance.value?.withdraw_balance}))
}));

const { resetForm, setFieldValue, values } = useForm({
  validationSchema: schema,
  initialValues: {
    address: '',
    amount: '',
    memo: '',
    password: '',
    addressLabel: ''
  }
})

/** 获取取款账号 */
const {
  runAsync: runAsyncWithdrawMethodList,
} = useRequest(ApiFinanceWithdrawMethodList)

/** 获取取款次数 */
const {
  runAsync: runAsyncWithdrawFeeInfo,
} = useRequest(ApiFinanceWithdrawFeeInfo)

/** 获取虚拟钱包列表 */
const {
  data: walletList,
  runAsync: runAsyncWalletList,
} = useRequest(ApiFinanceWithdrawWallet, {
  onSuccess(res) {
    if (res.d && res.d.length > 0) {
      const list = res.d.filter(a => a.state !== 2)
      // 判断列表中是否有默认地址，没有则选中第一个
      const defaultItem = list.find(i => i.is_default === 1)
      if (defaultItem){
        setFieldValue('address', defaultItem.id)
        setFieldValue('addressLabel', defaultItem.address)
      }
      else{
        setFieldValue('address', list[0].id)
        setFieldValue('addressLabel', list[0].address)
      }
    }else{
      resetForm({
        values: {
          ...values,         // 保留原有值
          amount: '',         // 覆盖要重置的字段
          memo: '',
          address: '',
        }
      })
    }
  },
})
const {
  runAsync: runAsyncWithdrawCoin,
  loading: withdrawLoading,
} = useRequest(ApiFinanceWithdrawCoin, {
  onSuccess(data, params) {
    setMaxAmount(false)
    appStore.getBalanceData()
  },
})

/** 虚拟钱包列表 */
const addrOptions = computed(() => {
  if (walletList.value && walletList.value.d) {
    return walletList.value.d.map((i) => {
      return {
        ...i,
        label: i.address,
        value: i.id,
        disabled: i.state === 2,
      }
    })
  }
  return []
})

watch(() => addrOptions, () => {
  if(addrOptions.value.length){
    setFieldValue('address', addrOptions.value[0].value)
    setFieldValue('addressLabel', addrOptions.value[0].label)
  }else{
    resetForm({
      values: {
        ...values,         // 保留原有值
        amount: '',         // 覆盖要重置的字段
        memo: '',
        address: '',
      }
    })
  }
}, {immediate: true})

// 协议列表
const curContractList = computed(() => {
  const currencyType = virCurrencyList.value.find(a => a.currency_id === activeVirCurrency.value.currency_id)?.currency_name
  return currencyType ? getVirtualCurrencyContractType(currencyType) : []
})
// 协议label
const currentNetworkLabel = computed(() => curContractList.value.find(a => a.value === currentNetwork.value)?.label ?? '')

function initNetwork() {
  const network = getVirtualCurrencyContractType(props.initVirCurrency.currency_name)
  return network ? network[0]?.value : ''
}
function onVirCurrencyChange(item: ICurrencyOption) {
  activeVirCurrency.value = item
  showSheet.value = false
  nextTick(() => {
    resetForm({
      values: {
        ...values,         // 保留原有值
        amount: '',         // 覆盖要重置的字段
        memo: ''
      }
    })
    setMaxAmount(false)
    getAllData()
  })
}
/** 获取当前日期：格式如YYYYMMDD */
function getCurDate() {
  const currentDate = new Date()
  const year = currentDate.getFullYear()
  const month = String(currentDate.getMonth() + 1).padStart(2, '0')
  const day = String(currentDate.getDate()).padStart(2, '0')
  return `${year}${month}${day}`
}
function onAddressClick(item: IVirAddressOption) {
  if (item.disabled)
    return
  setFieldValue('address', item.value)
  setFieldValue('addressLabel', item.label)
  showAddressSheet.value = false
}
function maxNumber() {
  setMaxAmount(false)
  setFieldValue('amount', maxAmount.value)
}
const amountSelectList = computed(() => {
  return [
    {label: t('min_value'), value: minWithdraw.value},
    {label: '25%', value: Number(maxAmount.value) * 0.25},
    {label: '50%', value: Number(maxAmount.value) * 0.5},
    {label: t('max_value'), value: Number(maxAmount.value)},
  ]
})
watch(selectedAmount, () => {
  setFieldValue('amount', selectedAmount.value)
})
async function handleWithdraw() {
  const { values } = withdrawFormRef.value
  /** 增加kyc逻辑 */
  if (isLogin.value && isKYCVerifyOpen.value && !isCompleteKYC.value)
    return openKYCDialog()

  runAsyncWithdrawFeeInfo({ currency_id: activeVirCurrency.value.currency_id }).then((data): void => {
    if (data.withdraw_setting_count > 0 && data.withdraw_count >= data.withdraw_setting_count && !Local.get(STORAGE_DEPOSIT_COUNT + getCurDate() + data.withdraw_count)?.value) {
      openPromptDialog(data)
      Local.set(STORAGE_DEPOSIT_COUNT + getCurDate() + data.withdraw_count, data.withdraw_count)
    }
    else {
      runAsyncWithdrawCoin({
        currency_id: Number(activeVirCurrency.value.currency_id),
        contract_id: currentNetwork.value,
        amount: values.amount.toString(),
        pay_password: values.password,
        wallet_id: addrOptions.value.find(item => item.label === values.address)?.id || '',
        auth_type: 2,
        auth_code: values.password,
        memo: values.memo || undefined,
      }).then(() => {
        message.success('取款成功')
      })
    }
  })
}
// 获取数据
async function getAllData() {
  isDataLoading.value = true
  return Promise.allSettled([
    runWithdrawBalance({ currency_id: activeVirCurrency.value.currency_id }),
    runAsyncWithdrawMethodList({ currency_id: activeVirCurrency.value.currency_id, contract_id: currentNetwork.value }),
    runAsyncWalletList({ currency_id: activeVirCurrency.value.currency_id, contract_type: currentNetwork.value }),
  ]).finally(() => {
    isDataLoading.value = false
  })
}
// 切换网络
function onNetworkChange(item: {label: string, value: string}) {
  currentNetwork.value = item.value
  showSheet.value = false
  nextTick(async () => {
    isDataLoading.value = true
    return Promise.allSettled([
      runAsyncWithdrawMethodList({ currency_id: activeVirCurrency.value.currency_id, contract_id: currentNetwork.value }),
      runAsyncWalletList({ currency_id: activeVirCurrency.value.currency_id, contract_type: currentNetwork.value }),
    ]).finally(() => {
      isDataLoading.value = false
    })
  })
}

watch(curContractList, (a) => {
  if (a && a.length > 0)
    currentNetwork.value = a && a.length > 0 ? a[0].value : ''
})
// 余额有变化，打码信息更新
watch(() => balanceData.value, () => {
  nextTick(() => {
    runWithdrawBalance({ currency_id: activeVirCurrency.value.currency_id })
  })
})
onActivated(async () => {
  await application.allSettled([
    runWithdrawBalance({ currency_id: activeVirCurrency.value.currency_id }),
    runAsyncWithdrawMethodList({ currency_id: activeVirCurrency.value.currency_id, contract_id: currentNetwork.value }),
    runAsyncWalletList({ currency_id: activeVirCurrency.value.currency_id, contract_type: currentNetwork.value }),
  ])
})
await application.allSettled([
  runWithdrawBalance({ currency_id: activeVirCurrency.value.currency_id }),
  runAsyncWithdrawMethodList({ currency_id: activeVirCurrency.value.currency_id, contract_id: currentNetwork.value }),
  runAsyncWalletList({ currency_id: activeVirCurrency.value.currency_id, contract_type: currentNetwork.value }),
])
</script>

<template>
  
  <div class="m-[1rem] p-[1rem] rounded-[.5rem] bg-bg-black-4 mb-[3.75rem]">
      <BaseInput required :label="t('withdraw_currency')" name="currency_name" :modelValue="activeVirCurrency?.currency_name"  @click="showSheet = true; sheetType = SheetType.CURRENCY" type="select">
        <template v-slot:left-icon>
          <AppCurrencyIcon class="size-[1.25rem]" :currency-type="getCurrencyConfigByCode(activeVirCurrency?.currency_id)?.['name']"/>
        </template>
      </BaseInput>
      <BaseInput required class="mt-[1rem]" :label="t('recharge_choose_chain')" name="currentNetworkLabel" :modelValue="currentNetworkLabel"  @click="sheetType = SheetType.CHAIN; showSheet = true" type="select">
      </BaseInput>
      <BaseSheet
        v-model="showSheet"
        :title="sheetType === SheetType.CURRENCY ? t('recharge_choose_currency') : t('recharge_choose_chain')"
        :showSearch="sheetType === SheetType.CURRENCY"
        :filterKey="sheetType === SheetType.CURRENCY ? 'currency_name' : 'label'"
        :items="sheetType === SheetType.CURRENCY ? virCurrencyList : curContractList"
      >
        <template v-slot="{ item }">
          <li
            class="mx-[0.875rem] h-[2.5rem] px-[0.5rem] rounded-[0.375rem] flex items-center justify-between"
            :class="[sheetType === SheetType.CURRENCY ? 
            (item.currency_id === activeVirCurrency.currency_id && 'bg-bg-black-4'):
            (item.value === currentNetwork && 'bg-bg-black-4')]"
            @click="sheetType === SheetType.CURRENCY ? onVirCurrencyChange(item) : onNetworkChange(item)"
          >
            <div class="flex items-center gap-[.1875rem]">
              <!-- 货币图标 -->
              <AppCurrencyIcon class="size-[1.25rem]" v-if="sheetType === SheetType.CURRENCY"
                :currency-type="getCurrencyConfigByCode(item.currency_id)?.['name']" />
              <span class="font-medium text-text-white-1 text-[1rem] ml-[.5rem]">{{ item.currency_name || item.label }}</span>
            </div>
            <span class="text-text-white-1 text-[1rem]" v-if="sheetType === SheetType.CURRENCY">{{ item.amount }}</span>
            <div class="size-[1rem] border-[.1875rem] border-brand rounded-[50%]"
              v-if="sheetType === SheetType.CHAIN && item.value === currentNetwork"></div>
          </li>
        </template>
      </BaseSheet>
      <Form :validation-schema="schema" v-if="addrOptions.length" @submit="handleWithdraw" ref="withdrawFormRef">
        <BaseInput required :label="t('withdraw_address')" name="address" :modelValue="values.addressLabel"  @click="showAddressSheet = true" class="mt-[1rem]" type="select">
        </BaseInput>
        <BaseSheet
          v-model="showAddressSheet"
          :title="t('choose_wallet')"
          :items="addrOptions"
        >
          <template v-slot="{ item, index }">
            <div v-if="index === 0" class="flex justify-between mb-[1.25rem]">
              <BaseButton class="h-[1.75rem] w-[3.875rem] ml-[.875rem] !rounded-[.25rem]" html-type="button" type="secondary" @click="showAddressSheet = false; router.push({
                path: 'withdraw/address-list', 
                query: {currency_id: activeVirCurrency.currency_id, contract_type: currentNetwork, currency_name: activeVirCurrency.currency_name}
              })">
                <BaseIcon name="uni-manage" class="text-text-black-10" />
                <span class="text-text-black-10 text-[.75rem] ml-[.25rem]">{{t('common_manage')}}</span>
              </BaseButton>
              <BaseButton class="h-[1.75rem] w-[3.875rem] mr-[.875rem] !rounded-[.25rem]" html-type="button" type="secondary" @click="showAddressSheet = false; router.push({
                path: 'withdraw/address',
                query: {
                  currency_id: activeVirCurrency?.currency_id,
                  contract_type: currentNetwork
                }
              })">
                <BaseIcon name="uni-plus" class="text-text-black-10 size-[1rem]" />
                <span class="text-text-black-10 text-[.75rem] ml-[.25rem]">{{t('common_add')}}</span>
              </BaseButton>
            </div>
            <li
              class="px-[1rem] flex items-center justify-between"
              :class="[item.value === values.address && 'bg-bg-black-4 shadow-[0_-1px_0_0,0_1px_0_0] shadow-bg-black-4']"
              @click="onAddressClick(item)"
            >
              <AppAddressSelectItem :currency_name="activeVirCurrency?.currency_name" :contract_name="currentNetworkLabel" :address="item.label"/>
            </li>
          </template>
        </BaseSheet>
        <BaseInput required class="mt-[1rem]" :label="t('withdraw_amount')" name="amount" :modelValue="values.amount" :placeholder="t('withdraw_amount_placeholder')" type="number">
          <template v-slot:label-right>
            <div class="text-text-white-2 font-[700]">{{t('max_withdraw_amount')}} <span class="text-function-red">{{ maxAmount }}</span></div>
          </template>
        </BaseInput>
        <AppWithdrawSelectAmount v-model="selectedAmount" :list="amountSelectList" class="mt-[0.5rem]" v-if="+maxAmount > 0"/>
        <BaseInput required class="mt-[1rem]" :label="t('money_password')" name="password" :modelValue="values.password" :placeholder="t('money_password_placeholder')" type="password">
        </BaseInput>
        <BaseInput required class="mt-[1rem]" :label="t('remark')" name="memo" :placeholder="t('remark')" v-if="isEOS">
        </BaseInput>
        <BaseButton class="w-full h-[2.5rem] mt-[1rem]" html-type="submit" :loading="withdrawLoading">
          <span class="text-text-black-10 text-[.75rem] mr-[.25rem]">{{t('common_confirm_submit')}}</span>
        </BaseButton>
      </Form>
      <template v-else>
        <BaseInput class="mt-[1rem]" :label="t('withdraw_address')" name="address" :placeholder="t('bind_withdraw_account_tip')" disabled>
        </BaseInput>
        <BaseInput class="mt-[1rem]" :label="t('withdraw_amount')" name="amount" :placeholder="t('withdraw_amount_placeholder')">
        </BaseInput>
        <BaseButton class="w-full h-[2.5rem] mt-[1rem]" html-type="submit" @click="router.push({
          path: 'withdraw/address',
          query: {
            currency_id: activeVirCurrency?.currency_id,
            contract_type: currentNetwork
          }
        })">
          <span class="text-text-black-10 text-[.75rem] mr-[.25rem]">{{t('bind_withdraw_address')}}</span>
        </BaseButton>
      </template>
  </div>

</template>
